"use client"

import { useState, useEffect } from "react"
import { getArtists, getFeaturedArtists } from "@/lib/api-client"
import type { Artist } from "@/types/artist"
import { Button } from "@/components/ui/button"
import { ArtisCategories } from "@/components/artist/artist-categories"
import { ArtistCard } from "@/components/artist-card"
import { Skeleton } from "@/components/ui/skeleton"
import { RegionLanguageFilter } from "@/components/filters/region-language-filter"
import { LanguageId, RegionId } from "@/types/region-language"
import type { ArtistGenreId } from "@/types/artist-genre"

export default function ArtistsPage() {
    const [artists, setArtists] = useState<Artist[]>([])
    const [featuredArtists, setFeaturedArtists] = useState<Artist[]>([])
    const [loading, setLoading] = useState(true)
    const [error, setError] = useState<string | null>(null)
    const [selectedGenreId, setSelectedGenreId] = useState<ArtistGenreId | null>(null)
    // 语言和区域筛选
    const [selectedLanguageId, setSelectedLanguageId] = useState<LanguageId>(LanguageId.ALL)
    const [selectedRegionId, setSelectedRegionId] = useState<RegionId>(RegionId.ALL)
    const [userId, setUserId] = useState<string | undefined>(undefined)

    // 精选歌手分页
    const [currentPage, setCurrentPage] = useState(1)
    const [totalPages, setTotalPages] = useState(1)
    const [, setTotalCount] = useState(0)
    const itemsPerPage = 5 // 每页显示5个精选歌手

    // 全部歌手分页
    const [artistsCurrentPage, setArtistsCurrentPage] = useState(1)
    const [artistsTotalPages, setArtistsTotalPages] = useState(1)
    const [, setArtistsTotalCount] = useState(0)
    const artistsPerPage = 10 // 每页显示10个歌手

    // 处理语言选择变化
    const handleLanguageChange = (languageId: LanguageId) => {
        setSelectedLanguageId(languageId)
        setCurrentPage(1) // 重置精选歌手页码
        setArtistsCurrentPage(1) // 重置全部歌手页码
    }

    // 处理区域选择变化
    const handleRegionChange = (regionId: RegionId) => {
        setSelectedRegionId(regionId)
        setCurrentPage(1) // 重置精选歌手页码
        setArtistsCurrentPage(1) // 重置全部歌手页码
    }

    // 精选歌手翻页
    const handlePrevPage = () => {
        if (currentPage > 1) {
            setCurrentPage(currentPage - 1)
        }
    }

    const handleNextPage = () => {
        if (currentPage < totalPages) {
            setCurrentPage(currentPage + 1)
        }
    }

    // 全部歌手翻页
    const handleArtistsPrevPage = () => {
        if (artistsCurrentPage > 1) {
            setArtistsCurrentPage(artistsCurrentPage - 1)
        }
    }

    const handleArtistsNextPage = () => {
        if (artistsCurrentPage < artistsTotalPages) {
            setArtistsCurrentPage(artistsCurrentPage + 1)
        }
    }

    useEffect(() => {
        // Get user ID from localStorage or other auth state management
        const storedUserId = localStorage.getItem("userId")
        if (storedUserId) {
            setUserId(storedUserId)
        }
    }, [])

    // 获取精选歌手数据
    useEffect(() => {
        const fetchFeaturedArtists = async () => {
            setLoading(true)
            try {
                // 获取精选歌手
                const response = await getFeaturedArtists({
                    limit: itemsPerPage,
                    page: currentPage,
                    languageId: selectedLanguageId !== LanguageId.ALL ? selectedLanguageId : undefined,
                    regionId: selectedRegionId !== RegionId.ALL ? selectedRegionId : undefined,
                })
                // 如果返回的是包含分页信息的对象
                setFeaturedArtists(response.data.items || [])
                setTotalCount(response.data.total || 0)
                setTotalPages(Math.ceil((response.data.total || 0) / itemsPerPage))
                setError(null)
            } catch (err) {
                console.error("获取精选歌手失败:", err)
                setError("获取精选歌手失败，请稍后重试")
                setFeaturedArtists([])
            } finally {
                setLoading(false)
            }
        }

        fetchFeaturedArtists()
    }, [currentPage, selectedLanguageId, selectedRegionId, itemsPerPage])

    // 获取全部歌手数据
    useEffect(() => {
        const fetchAllArtists = async () => {
            setLoading(true)
            try {
                // 获取所有歌手
                const response = await getArtists({
                    page: artistsCurrentPage,
                    limit: artistsPerPage,
                    languageId: selectedLanguageId !== LanguageId.ALL ? selectedLanguageId : undefined,
                    regionId: selectedRegionId !== RegionId.ALL ? selectedRegionId : undefined,
                    genreId: selectedGenreId,
                })
                // 如果返回的是包含分页信息的对象
                setArtists(response.data.items || [])
                setArtistsTotalCount(response.data.total || 0)
                setArtistsTotalPages(Math.ceil((response.data.total || 0) / artistsPerPage))
                setError(null)
            } catch (err) {
                console.error("获取歌手数据失败:", err)
                setError("获取歌手数据失败，请稍后重试")
                setArtists([])
            } finally {
                setLoading(false)
            }
        }

        fetchAllArtists()
    }, [artistsCurrentPage, selectedLanguageId, selectedRegionId, selectedGenreId, artistsPerPage])

    return (
        <div className="container mx-auto px-4 py-6">
            {/* 语言和地区筛选 */}
            <RegionLanguageFilter
                onLanguageChange={handleLanguageChange}
                onRegionChange={handleRegionChange}
                initialLanguageId={selectedLanguageId}
                initialRegionId={selectedRegionId}
            />

            {/* 精选歌手 */}
            <div className="mb-8">
                <div className="flex justify-between items-center mb-6">
                    <h2 className="text-2xl font-bold">精选歌手</h2>
                </div>

                <div className="relative">
                    {/* 左翻页按钮 */}
                    {currentPage > 1 && (
                        <button
                            onClick={handlePrevPage}
                            className="absolute left-[-20px] top-[50%] transform -translate-y-1/2 z-10 bg-white rounded-full p-2 shadow-lg"
                            aria-label="上一页"
                        >
                            <svg
                                xmlns="http://www.w3.org/2000/svg"
                                className="h-6 w-6 text-primary"
                                fill="none"
                                viewBox="0 0 24 24"
                                stroke="currentColor"
                            >
                                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 19l-7-7 7-7" />
                            </svg>
                        </button>
                    )}

                    {/* 歌手列表 */}
                    <div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-5 gap-4">
                        {loading ? (
                            // 加载状态显示骨架屏
                            Array(itemsPerPage)
                                .fill(0)
                                .map((_, index) => (
                                    <div key={index} className="flex flex-col items-center">
                                        <Skeleton className="h-40 w-40 rounded-full mb-3" />
                                        <Skeleton className="h-4 w-24 mb-2" />
                                        <Skeleton className="h-3 w-16" />
                                    </div>
                                ))
                        ) : featuredArtists.length > 0 ? (
                            featuredArtists.map((artist) => <ArtistCard key={artist.id} artist={artist} userId={userId} />)
                        ) : (
                            <div className="col-span-5 text-center py-10 text-gray-500">暂无精选歌手</div>
                        )}
                    </div>

                    {/* 右翻页按钮 */}
                    {currentPage < totalPages && (
                        <button
                            onClick={handleNextPage}
                            className="absolute right-[-20px] top-[50%] transform -translate-y-1/2 z-10 bg-white rounded-full p-2 shadow-lg hover:bg-gray-100 transition-colors"
                            aria-label="下一页"
                        >
                            <svg
                                xmlns="http://www.w3.org/2000/svg"
                                className="h-6 w-6 text-primary"
                                fill="none"
                                viewBox="0 0 24 24"
                                stroke="currentColor"
                            >
                                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 5l7 7-7 7" />
                            </svg>
                        </button>
                    )}
                </div>
            </div>

            {/* 歌手分类 */}
            <div className="mb-8">
                <h2 className="text-2xl font-bold mb-4">歌手分类</h2>
                <ArtisCategories
                    selectedGenreId={selectedGenreId}
                    onGenreChange={(genreId) => {
                        setSelectedGenreId(genreId)
                        setArtistsCurrentPage(1) // 重置全部歌手页码
                    }}
                />
            </div>

            {/* 全部歌手 */}
            <div>
                <div className="flex justify-between items-center mb-6">
                    <h2 className="text-2xl font-bold">全部歌手</h2>
                    <div className="flex space-x-2">
                        <Button variant="outline" size="sm">
                            最新
                        </Button>
                        <Button variant="outline" size="sm">
                            最热
                        </Button>
                    </div>
                </div>

                {error ? (
                    <div className="text-center py-8 text-red-500">{error}</div>
                ) : (
                    <div className="relative">
                        {/* 左翻页按钮 */}
                        {artistsCurrentPage > 1 && (
                            <button
                                onClick={handleArtistsPrevPage}
                                className="absolute left-[-20px] top-[50%] transform -translate-y-1/2 z-10 bg-white rounded-full p-2 shadow-lg"
                                aria-label="上一页"
                            >
                                <svg
                                    xmlns="http://www.w3.org/2000/svg"
                                    className="h-6 w-6 text-primary"
                                    fill="none"
                                    viewBox="0 0 24 24"
                                    stroke="currentColor"
                                >
                                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 19l-7-7 7-7" />
                                </svg>
                            </button>
                        )}

                        {/* 歌手列表 */}
                        <div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-5 gap-4">
                            {loading ? (
                                // 加载状态显示骨架屏
                                Array(artistsPerPage)
                                    .fill(0)
                                    .map((_, index) => (
                                        <div key={index} className="flex flex-col items-center">
                                            <Skeleton className="h-40 w-40 rounded-full mb-3" />
                                            <Skeleton className="h-4 w-24 mb-2" />
                                            <Skeleton className="h-3 w-16" />
                                        </div>
                                    ))
                            ) : artists.length > 0 ? (
                                artists.map((artist) => <ArtistCard key={artist.id} artist={artist} userId={userId} />)
                            ) : (
                                <div className="col-span-5 text-center py-10 text-gray-500">暂无歌手</div>
                            )}
                        </div>

                        {/* 右翻页按钮 */}
                        {artistsCurrentPage < artistsTotalPages && (
                            <button
                                onClick={handleArtistsNextPage}
                                className="absolute right-[-20px] top-[50%] transform -translate-y-1/2 z-10 bg-white rounded-full p-2 shadow-lg hover:bg-gray-100 transition-colors"
                                aria-label="下一页"
                            >
                                <svg
                                    xmlns="http://www.w3.org/2000/svg"
                                    className="h-6 w-6 text-primary"
                                    fill="none"
                                    viewBox="0 0 24 24"
                                    stroke="currentColor"
                                >
                                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 5l7 7-7 7" />
                                </svg>
                            </button>
                        )}
                    </div>
                )}
            </div>
        </div>
    )
}

